package umt.cs.cs241.assignment3b.c_3_17;

import java.util.Random;

public class EvenOddSwap {
	
	private int [] values;
	private int arraySize;
	
	public EvenOddSwap(){
		
		arraySize = 30;
		values = getRandomIntArray(arraySize);
		
		this.swapEvenOdd(0);
		this.print();
		
	}
	
	private void swapEvenOdd(int iterator){
		
		int swap;
		
		//If Odd, loop through array until an even is found and swap
		if((values[iterator] % 2) != 0){
			for(int i = iterator; i < values.length; i++ ){
				
				//If element at index i is even, swap
				if((values[i] % 2) == 0){
					swap = values[i];
					values[i] = values[iterator];
					values[iterator] = swap;
				}
			}
		}
		
		//If iterator is less than array length, increment and make recursive call
		if(iterator < (values.length - 1)){
			iterator++;
			this.swapEvenOdd(iterator);
		}
	}
	
	//Alternative method that uses a while loop
	private void swapEvenOddAlt(int iterator){
		
		int swap1;
		int swap2;
		int index = iterator;
		
		//Base Case
		if(iterator < values.length){
			
			//Test the value of the element at iterator in values[].  
			//If it is odd, loop until an even value is found and swap.
			while((values[iterator] % 2) != 0 && index < values.length){
				
				//Swap an even value is found
				if((values[index] % 2) == 0){
					swap1 = values[iterator];
					swap2 = values[index];
					values[iterator] = swap2;
					values[index] = swap1;
				}
				index++;
			}
			//Advance the iterator and make recursive call
			iterator++;
			this.swapEvenOddAlt(iterator);
		}
	}

	
	private void print(){
		for(int i = 0; i < values.length; i++){
			System.out.print(values[i] + " ");
		}
	}
	
	/**
	 * Returns an array of random int values with an array size specified by the user.
	 * 
	 * @param arraySize The number of values a user wishes to place in the returned array.
	 * @return randomNumbers An array of random number values
	 */
	private int[] getRandomIntArray(int arraySize){
		
		Random randomGen = new Random();
		
		int [] randomNumbers = new int[arraySize];
		
		for(int i = 0; i < (arraySize - 1); i++){
			randomNumbers[i] = randomGen.nextInt(50) + 1;
		}
		
		return randomNumbers;
		
	}
	
}
